package servlet;

import myutil.FileUtil;
import myutil.HttpUrlUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/analysis")
public class FeatureAnalysisServlet extends HttpServlet {
private static final String APPID = "80fd2613";
private static final String APIKey = "ca4a5426bdcccf03057e66573dd2df82";
private static final String AGE_URL = "http://tupapi.xfyun.cn/v1/age";
private static final String Yan_URl = "http://tupapi.xfyun.cn/v1/face_score";
private static final String sex_URl = "http://tupapi.xfyun.cn/v1/sex";
private static final String expr_URL = "http://tupapi.xfyun.cn/v1/expression";

//    人脸特征分析
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String path = req.getServletContext().getRealPath("/uploadFile/feature.jpg");
    Map<String, String> headerMap = buildHttpHeader();
    byte[] imgs = FileUtil.read(path);// 读取文件内容为二进制数组
    String ageResult = HttpUrlUtil.handleHttpRequest(AGE_URL, headerMap, imgs);// 发起请求，获取结果
    String sexResult = HttpUrlUtil.handleHttpRequest(sex_URl, headerMap, imgs);// 发起请求，获取结果
    String YanResult = HttpUrlUtil.handleHttpRequest(Yan_URl, headerMap, imgs);// 发起请求，获取结果
    String exprResult = HttpUrlUtil.handleHttpRequest(expr_URL, headerMap, imgs);// 发起请求，获取结果

//        System.out.println(ageResult);
//        System.out.println(sexResult);
//        System.out.println(YanResult);
//        System.out.println(exprResult);

    JSONObject age = (JSONObject) JSONObject.parse(ageResult);
//        System.out.println("code"+age.get("code"));

    //解析age的范围
    /*JSONObject agedata = (JSONObject) age.get("data");
    JSONArray agefile = (JSONArray) agedata.get("fileList");
    JSONObject agelabel = (JSONObject) agefile.get(0);
    String ageLabelStr = agelabel.get("label").toString();

    System.out.println(agelabel.get("label").toString());

    //解析性别的值
    JSONObject sex = (JSONObject) JSONObject.parse(sexResult);
    JSONObject sexdata = (JSONObject) sex.get("data");
    JSONArray sexFileList = (JSONArray) sexdata.get("fileList");
    JSONObject SexLable = (JSONObject) sexFileList.get(0);


    String sexLabelStr = SexLable.get("label").toString();


//        SexLable.get("label");
    System.out.println(SexLable.get("label").toString());

    //解析颜值的值
    JSONObject yanzhi = (JSONObject) JSONObject.parse(YanResult) ;
    JSONObject yanzhidata = (JSONObject) yanzhi.get("data");
    JSONArray YList = (JSONArray) yanzhidata.get("fileList");
    JSONObject YZData = (JSONObject) YList.get(0);
    String yanzhiStr =YZData.get("label").toString();
    System.out.println(YZData.get("label"));

    //解析表情的是数据
    JSONObject bq = (JSONObject) JSONObject.parse(exprResult);//{"code":0,"data":{"fileList":[{"label":5,"labels":[5,4,12,3,2],"name":"feature.jpg","rate":0.5475529432296753,"rates":[0.5475529432296753,0.1869661509990692,0.13573810458183289,0.05459864065051079,0.02603793516755104],"review":false}],"reviewCount":0,"topNStatistic":[{"count":1,"label":5}]},"desc":"success","sid":"tup000011b9@dx35331520dc14a00100"}

    JSONObject bqdata = (JSONObject) bq.get("data");
    JSONArray bqList = (JSONArray) bqdata.get("fileList");
    JSONObject bqlabel = (JSONObject) bqList.get(0);
    System.out.println(bqlabel.get("label"));
    String bqStr = bqlabel.get("label").toString();*/

String ageJ=json(ageResult);
String sex= json(sexResult);
String Yz=json(YanResult);
String  bq= json(exprResult);

    // 打印输出结果
    // TODO 把结果响应给前端
JSONObject returnJsonObj = new JSONObject();
returnJsonObj.put("code",age.get("code"));
returnJsonObj.put("label",ageJ);
returnJsonObj.put("sexlabel",sex);
returnJsonObj.put("yzlabel",Yz);
returnJsonObj.put("bqlabel",bq);
resp.getWriter().write(returnJsonObj.toJSONString());
//    resp.getWriter().write(returnJsonObj.toJSONString());

    return;
}
private Map<String,String>buildHttpHeader() throws UnsupportedEncodingException {
    String imageName = "/uploadFile/feature.jpg";
    String curTime = System.currentTimeMillis() / 1000L + "";
    String param = "{\"image_name\":\"" + imageName + "\"}";
//        String paramBase64 = new String(Base64.encode(param.getBytes("UTF-8")));
    String paramBase64 = new String(Base64.encodeBase64(param.getBytes("UTF-8")));
    String checkSum = DigestUtils.md5Hex(APIKey + curTime + paramBase64);
    Map<String, String> header = new HashMap<String, String>();
    header.put("Conten-Type", "application/x-www-form-urlencoded;charset=urf-8");
    header.put("X-Param", paramBase64);
    header.put("X-CurTime", curTime);
    header.put("X-CheckSum", checkSum);
    header.put("X-Appid", APPID);
    return header;
}
private String json(String url){
    JSONObject age = (JSONObject) JSONObject.parse(url);
    JSONObject agedata = (JSONObject) age.get("data");
    JSONArray agefile = (JSONArray) agedata.get("fileList");
    JSONObject agelabel = (JSONObject) agefile.get(0);
//        return agelabel;
    String ageLabelStr = agelabel.get("label").toString();
    return ageLabelStr;
}


}
